<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_employee'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="hAdd">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table :data="list" style="100%" :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
          <el-table-column label="序号" type="index" :index="orderIndex" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <!-- :current-page 设置当前的页码
              :page-sizes 可供选中的每页的条数
              :page-size 当前每页的条数''
              layout 决定布局元素的顺序
              total 一共有的多少条数据

               @size-change : 页码变换时
                @current-change: @size-change 每天显示多少条,变化时触发
             -->
          <el-pagination
            :current-page="pageParams.page"
            :page-sizes="[2, 3, 5, 10]"
            :page-size="pageParams.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>

    <!-- 弹窗 -->
    <el-dialog title="新增员工" :visible.sync="showHide">
      <empDialog v-if="showHide" @close="hClose" @success="hSuccess" />
    </el-dialog>

    <!-- 分配角色弹窗 -->
    <el-dialog title="分配角色" :visible.sync="showDialogRole">
      <assign-role v-if="showDialogRole" :employee-id="curEmployeId" @close="showDialogRole=false" />
    </el-dialog>

  </div>
</template>

<script>
import AssignRole from './assignRole.vue'
import empDialog from './empDialog.vue'
import dayjs from 'dayjs'
import { getEmployeeList, delEmployee } from '@/api/employees'
import employees from '@/constant/employees'

const map = employees.hireType.reduce((acc, cur) => {
  acc[cur.id] = cur.value
  return acc
}, {})

export default {
  components: { empDialog, AssignRole },
  data() {
    return {
      curEmployeId: '', // 当前的员工编号
      showDialogRole: false,
      list: [],
      pageParams: {
        page: 1, // 查询第一页
        pagesize: 10 // 每页5条  --- 要与pagination中page-size一致
      },
      total: 0, // 总的数据条数
      showHide: false
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 点击分配角色
    hAssignRole({ id }) {
      console.log('当前要分配角色id是', id)
      this.showDialogRole = true
      this.curEmployeId = id
    },
    // 点击excel导出
    async handleDownload() {
      this.downloadLoading = true
      /*
        获取所有数据
         思路: 讲获取条数=total
      */
      const res = await getEmployeeList(this.pageParams.page, this.total)
      import('@/vendor/Export2Excel').then(excel => {
        // const list = this.list // 获取当前页的数据
        const list = res.data.rows // 获取所有数据
        const data = this.formatJson(list)
        const tHeader = this.tHeader
        console.log(data)
        excel.export_json_to_excel({
          header: tHeader, // 设置表头
          data, // 表体数据
          // filename: this.filename, // 设置导出文件名
          filename: '钱端87期', // 设置导出文件名
          autoWidth: this.autoWidth, // 定义表格宽度  默认是true
          bookType: this.bookType // 定义文件格式 默认是xlsx
          // bookType: 'txt' // 定义文件格式 默认是xlxs
        })
        this.downloadLoading = false
      })
    },
    formatJson(list) {
      // console.log(list, 6666)
      // 目的: 得到一个二维数组并返回,并且根据需求进行导出
      const map = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }

      this.tHeader = Object.values(map)

      return list.map(item => {
        // 1-获取键===>得到多少字段
        // 2-根据键获取值
        return Object.keys(map).map(key => {
          return item[key]
        })
      })
    },
    hSuccess() {
      this.showHide = false
      // 添加成功，进入最后一页看数据
      this.total++
      // 最后一页
      this.pageParams.page = Math.ceil(this.total / this.pageParams.pagesize)
      this.loadEmployeeList()
    },
    // 点击新增员工
    hAdd() {
      this.showHide = true
    },
    hClose() {
      this.showHide = false
    },
    // 点击删除按钮
    hDel(id) {
      this.$confirm('确认删除部门吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch(() => {

      })
    },
    async doDel(id) {
      await delEmployee(id)
      this.$message.success('删除成功')
      if (this.list.length === 1) {
        this.pageParams.page--
        if (this.pageParams.page <= 0) {
          this.pageParams.page = 1
        }
      }
      this.loadEmployeeList()
    },
    async loadEmployeeList() {
      const res = await getEmployeeList(this.pageParams.page, this.pageParams.pagesize)
      this.list = res.data.rows
      this.total = res.data.total
      res.data.rows.forEach(item => {
        item.timeOfEntry = dayjs(item.timeOfEntry).format('YYYY-MM-DD')
      })
      console.log(res, 77)
    },
    // 表单数据格式化
    format(id) {
      // console.log(id)

      return map[id] || '未知'
    },
    handleSizeChange(val) {
      this.pageParams.pagesize = val
      this.loadEmployeeList()
    },
    // 点击页码
    handleCurrentChange(val) {
      // 1. 更新页码
      this.pageParams.page = val
      // 2. 重发请求
      this.loadEmployeeList()
    },
    // 优化分页
    orderIndex(e) {
      // console.log(e, 3)

      return e + 1 + (this.pageParams.page - 1) * this.pageParams.pagesize
    }
  }
}
</script>
